/*
 * @Author: Wilbur
 * @Date: 2019-04-02 14:34:01
 * @Last Modified by: Wilbur
 * @Last Modified time: 2019-05-16 11:15:12
 */

<template>
    <div class="container create-hire-wrap">
        <el-form
            v-if="init"
            ref="mainform"
            :model="formData"
            label-position="right"
            status-icon
            :rules="formRule"
            label-width="110px"
            :disabled="false">
            <!-- 广告主设置 -->
            <div class="form-unit">
                <div class="form-title">创建公司</div>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="company_name"
                    label="公司名称:">
                    <el-input
                        placeholder="必填"
                        v-model="formData.company_name"
                        size="small"
                        class="task-input"/>
                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="username"
                    label="登录账号:">
                    <el-input
                        placeholder="必填"
                        v-model="formData.username"
                        size="small"
                        class="task-input"/>
                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="password"
                    label="密码:">
                    <el-input
                        placeholder="必填"
                        v-model="formData.password"
                        size="small"
                        class="task-input"/>
                </el-form-item>

                <!-- <el-form-item
                    class="task-form-item"
                    size="small"
                    label="会员时间范围:">
                    <el-date-picker
                        v-model="formData.vipTime"
                        type="datetimerange"
                        range-separator="至"
                        size="small"
                        class="task-input"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间" />
                </el-form-item> -->

                <!-- <el-form-item
                    v-if="formData.vipTime.toString() != ','"
                    label="会员类型:"
                    class="task-form-item"
                    prop="vip">
                    <el-select
                        v-model="formData.vip"
                        size="small"
                        class="task-input"
                        placeholder="选择会员类型">
                        <el-option
                            label="无"
                            :value="0"/>
                        <el-option
                            label="1万/年版"
                            :value="1"/>
                        <el-option
                            label="1.5万/年版"
                            :value="2"/>
                        <el-option
                            label="2万元/年版"
                            :value="3"/>
                    </el-select>
                </el-form-item> -->
                <!-- <el-form-item
                    class="task-form-item"
                    v-if="formData.vipTime.toString() != ','"
                    size="small"
                    label="金额:">
                    <el-input
                        placeholder="金额"
                        v-model="formData.vip_money"
                        size="small"
                        class="task-input"/>
                </el-form-item> -->

                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="remark"
                    label="备注:">
                    <el-input
                        placeholder="非必填"
                        v-model="formData.remark"
                        type="textarea"
                        :rows="3"
                        size="small"
                        class="task-input"/>
                </el-form-item>

            </div>

            <div class="form-unit">
                <div class="operate-baar">
                    <el-button
                        size="medium"
                        v-show="hire_no ? false : true"
                        @click="fnReset()">重置</el-button>
                    <el-button
                        size="medium"
                        v-show="hire_no ? true : false"
                        @click="handleRoute('hireList')">返回</el-button>
                    <el-button
                        size="medium"
                        type="primary"
                        @click="fnSubmit()">提交</el-button>
                </div>
            </div>
        </el-form>
    </div>
</template>

<script>
export default {
    components: {},
    data() {
        var validateLinkUrl = (rule, val, callback) => {

            if(val.indexOf('http://') == -1){
                callback(new Error('错误'));
                return;
            }
            callback();
        };

        var validatePassword = (rule, value, callback) => {
            if (!this.hire_no && !value) {
                callback(new Error(rule.message));
            } else {
                callback();
            }
        };

        // 验证二位数组,且数组内元素不为空
        var validateArray = (rule, value, callback) => {
            if (!value) {
                callback(new Error(rule.message));
            } else {
                if (value.length < 2 || !value[0] || !value[1]) {
                    callback(new Error(rule.message));
                    return ;
                }
                callback();
            }
        };

        return {
            checkList: [1, 2],
            authResult: {},
            breadcrumbList: [
                {
                    title: "广告系统",
                },
                {
                    title: "广告主列表",
                    name: 'hireList',
                },
                {
                    title: '创建公司'
                }
            ],
            hire_no: '',
            provence: [],
            formData: {
                username: "",
                company_name: '',
                password: '',
                remark: ''
                // vip_start_time: '',
                // vip_expire_time: '',
                // vipTime: ['', ''],
                // vip: '',
                // vip_money: ''
            },
            formRule: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' }
                ],
                company_name: [
                    { required: true, message: '请输入公司名称', trigger: 'blur' }
                ],
                title: [
                    { required: true, message: '请输入标题', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在 1 到 20 个字', trigger: 'blur' }
                ],
                vipTime: [
                    { required: true, message: '请填写会员时间', trigger: 'blur' },
                    { validator: validateArray, message: '请填写正确的时间', trigger: 'blur' }
                ],
                password: [
                    { validator: validatePassword, message: '请填写账户密码', trigger: 'blur' }
                ],
            },
            submitting: false,
            init: false,

            baseUrl: '',
            sessionTicket: localStorage.getItem('sessionTicket'),
            escape: escape,
        };
    },
    created() {
        this.authResult = this.$route.meta.authResult;
        this.$store.commit('SET_HEADER', this.breadcrumbList);

        this.hire_no = this.$route.query.hire_no ? this.$route.query.hire_no : '';

        if (!this.hire_no) {
            this.init = true;
            this.fnInitTimeNow();
        }else{
            this.fnInitHireInfo();
        }
    },
    methods: {
        fnInitTimeNow() {
            var timeStart=new Date().getTime();
            var timeEnd = this.fnGetAfterNYear(this.getNowFormatDate(), 1);

            // this.formData.vipTime = [timeStart, timeEnd];
            // console.log(this.formData.vipTime);
        },
        getNowFormatDate() {
            var date = new Date();
            var seperator1 = "";
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var strDate = date.getDate();

            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var currentdate = year + seperator1 + month + seperator1 + strDate;

            return currentdate;
        },
        /**
		 * 计算N年后,YYYYMMDD
		 * startdate：为开始时间，格式YYYYMMDD
		 * nextYear：为间隔年月，如1表示一年后，2表示两年后
		 */
        fnGetAfterNYear(startdate,nextYear){
            var expriedYear = parseInt(startdate.substring(0,4)) + nextYear;
            var expriedMonth = startdate.substring(4,6);
            var expriedDay = startdate.substring(6);
            //考虑二月份场景，若N年后的二月份日期大于该年的二月份的最后一天，则取该年二月份最后一天

            if(expriedMonth == '02' || expriedMonth == 2){
                var monthEndDate = new Date(expriedYear ,expriedMonth,0).getDate();

                if(parseInt(expriedDay) > monthEndDate){//为月底时间
                    //取两年后的二月份最后一天
                    expriedDay = monthEndDate;
                }
            }
            return new Date(expriedYear+'-'+expriedMonth+'-'+expriedDay + ' ' + new Date().getHours()+ ':' + new Date().getMinutes() + ':' + new Date().getSeconds()).getTime();
        },
        fnInitTime(time) {
            if(time == 0) {
                return '';
            }else{
                return new Date(time * 1000);
            }
        },
        fnInitHireInfo() {
            this.$post('/wei4/hire_user%5Cget', {
                hire_no: this.hire_no
            }, resp => {
                if(resp.code == 1){
                    this.formData = {
                        ...resp.data,
                        company_name: resp.data.company.name,
                        // vipTime: [this.fnInitTime(resp.data.vip_start_time), this.fnInitTime(resp.data.vip_expire_time)]
                    };
                    this.init = true;
                }else{
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },
        fnSubmit(){
            if(this.submitting){
                return ;
            }
            this.$refs.mainform.validate(valid => {
                if(valid){
                    this.submitting = true;

                    let data = {
                        username: this.formData.username,
                        company_name: this.formData.company_name,
                        password: this.formData.password,
                        // vip: this.formData.vip,
                        // vip_money: this.formData.vip_money,
                        // vip_start_time: this.formData.vipTime == null ? '' : Date.parse(this.formData.vipTime[0])/1000,
                        // vip_expire_time : this.formData.vipTime == null ? '' : Date.parse(this.formData.vipTime[1])/1000,
                        remark: this.formData.remark,
                    };

                    if(this.hire_no){
                        data.hire_no = this.hire_no;

                        this.$post('/wei4/hire_user%5Cedit', data, resp => {
                            if(resp.code == 1){
                                this.$message({
                                    type: 'success',
                                    center: true,
                                    message: '修改成功'
                                });
                                this.$router.push({
                                    name: 'hireList'
                                });
                            }else{
                                this.$message({
                                    type: 'warning',
                                    center: true,
                                    message: resp.msg
                                });
                            }
                            this.submitting = false;
                        });
                    }else{
                        this.$post('/wei4/hire_user%5Cadd', data, resp => {
                            if(resp.code == 1){
                                this.$message({
                                    type: 'success',
                                    center: true,
                                    message: '操作成功'
                                });
                                this.$router.push({
                                    name: 'hireList'
                                });
                            }else{
                                this.$message({
                                    type: 'warning',
                                    center: true,
                                    message: resp.msg
                                });
                            }
                            this.submitting = false;
                        });
                    }

                }
            });
        },
        fnReset(){
            this.$refs.mainform.resetFields();
        },
        /**
       * 跳转页面
       */
        handleRoute(name, query) {
            let obj = {
                name
            };

            if (query) {
                obj.query = query;
            }

            this.$router.push(obj);
        },
    },
};
</script>

<style lang="less" scoped>
    .avatar{
        width: 100%;
        height: 100%;;
    }
    .margin-top{
        margin-top: 15px;
    }
    .create-hire-wrap {
      background: #fff;
      margin: 15px;
      margin-bottom: 0;
      padding: 30px;
      overflow: auto;
    }
    .form-unit {
      margin-bottom: 40px;
    }
    .form-title {
      font-size: 16px;
      font-weight: 600;
      color: rgba(0, 0, 0, 0.85);
      line-height: 18px;
      padding: 0 10px;
      border-left: 2px solid #1890ff;
      margin-bottom: 20px;
    }
    .task-input {
      width: 435px !important;
    }
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
      -webkit-appearance: none;
    }
    input[type="number"] {
      -moz-appearance: textfield;
    }

    .operate-baar {
      width: 100%;
      text-align: center;
      margin-top: 168px;
    }
</style>
<style lang="less">
</style>
